// KUKU 安全服务管理器主入口 - 模块化架构

use std::thread;
use std::time::Duration;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use log::{info, error};

// 导入KUKU服务层核心功能
use kuku_services::ServiceManager;

fn main() {
    info!("Starting KUKU Service Manager");
    info!("Architecture: Exokernel with Safe Rust Services");
    info!("OS Framework: Zig (Exokernel)");
    info!("OS Services: Safe Rust only - Modular Architecture");

    // 创建停止标志
    let running = Arc::new(AtomicBool::new(true));
    let running_clone = Arc::clone(&running);

    // 启动服务管理器线程
    let manager_thread = thread::spawn(move || {
        // 初始化服务管理器
        let service_manager = match ServiceManager::new() {
            Ok(manager) => manager,
            Err(err) => {
                error!("Failed to initialize service manager: {}", err);
                return;
            }
        };

        info!("Service manager initialized successfully");

        // 启动所有服务
        if let Err(err) = service_manager.start_all_services() {
            error!("Failed to start all services: {}", err);
            return;
        }

        info!("All services started successfully");

        // 主循环
        while running_clone.load(Ordering::Relaxed) {
            // 短暂休眠，避免CPU占用过高
            thread::sleep(Duration::from_millis(100));
        }

        info!("Service manager shutdown completed");
    });

    // 设置简单的信号处理
    let running_main = Arc::clone(&running);
    ctrlc::set_handler(move || {
        info!("Received shutdown signal");
        running_main.store(false, Ordering::Relaxed);
    }).expect("Error setting Ctrl-C handler");

    // 等待服务管理器线程结束
    if let Err(err) = manager_thread.join() {
        error!("Service manager thread panicked: {:?}", err);
    }

    info!("KUKU Service Manager stopped");
}